package com.ptswitch.material.pages.security;

import java.util.List;

import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.hxzon.tapestry5.model.ValueGrouper;
import org.hxzon.tapestry5.model.ValueLabel;
import org.slf4j.Logger;

import com.ptswitch.material.model.common.Uzer;
import com.ptswitch.material.model.security.Role;
import com.ptswitch.material.pages.base.PageBase;
import com.ptswitch.material.service.LoginInfoService;
import com.ptswitch.material.service.RoleService;
import com.ptswitch.material.service.UserService;
import com.ptswitch.material.util.HlogConstants;
import com.ptswitch.material.util.ValueLabelUtil;
import com.ptswitch.material.util.security.PermissionUtil;
import com.ptswitch.material.util.security.RoleEditUtil;
import com.ptswitch.material.util.security.RoleUtil;

public class EditUser extends PageBase {
    @Inject
    private Logger logger;
    @Inject
    private UserService userSer;
    @Inject
    private RoleService roleSer;
    @Inject
    private LoginInfoService loginInfoSer;
    @InjectPage
    private ListUser listUser;
    //
    @Property
    private Uzer user;
    @Property
    private List<Role> userRoles;
    @Property
    private List<Role> roles;
    @Property
    private ValueLabel<Role> roleLabel = ValueLabelUtil.roleLabel;
    @Property
    private ValueGrouper<Role> roleGrouper = RoleUtil.roleValueGrouper;

    @OnEvent(value = EventConstants.ACTIVATE)
    Object init(long id) {
        checkPermitted(PermissionUtil.UserEdit);
        //init for display or update
        user = userSer.findById(id);
        userRoles = RoleEditUtil.getRoles(user);
        roles = roleSer.findNormalRoles();
        return null;
    }

    @OnEvent(value = EventConstants.PASSIVATE)
    Object onPassivate() {
        return user.getId();
    }

    @OnEvent(value = EventConstants.SUCCESS, component = "update")
    Object update() {
        checkPermitted(PermissionUtil.UserEdit);
        userSer.save(user);
        roleSer.saveUserRoles(RoleEditUtil.toNewUserRoles(userRoles,//
                user.getRoles(), user));
        hlog(HlogConstants.updateUser, user);
        return listUser;
    }

    @OnEvent(value = EventConstants.SUCCESS, component = "changePassword")
    Object changePassword() {
        checkPermitted(PermissionUtil.UserChangePassword);
        user.md5password();
        userSer.save(user);
        loginInfoSer.deleteByUsername(user.getUsername());
        hlog(HlogConstants.updateUserPassword, user);
        return listUser;
    }
}
